<script>
import { needRequestToken } from './utils/auth'
import { getSite } from '@/api'

export default {
  // 小程序启动程序
  async onLaunch () {
    console.group('MP onLanuch')
    console.log('小程序启动程序')
    // 获取设备布局信息
    mpvue.setStorageSync('menuButtonObject', wx.getMenuButtonBoundingClientRect())
    this.$store
      .dispatch('app/setMenuButton', wx.getMenuButtonBoundingClientRect())
      .then(res => {
        console.log(res)
      })
    wx.getSystemInfo({
      success: data => {
        mpvue.setStorageSync('systemData', data)
        console.log('to store systemData:-------')

        this.$store
          .dispatch('app/setDevice', data)
          .then(res => {
            console.log(res)
          })
      }
    })
    // 判断请求token是否过期
    needRequestToken()
    getSite().then(res => {
      if (res.share_data) {
        mpvue.setStorageSync('shareData', res.share_data)
      }
      if (res.work_types) {
        this.$store.dispatch('app/setWorkTypes', res.work_types)
      }
    })
    // 监听网络连接状态
    wx.onNetworkStatusChange((res) => {
      if (!res.isConnected) {
        wx.showToast({
          title: '网络连接失败，请检查网络连接',
          icon: 'none',
          duration: 3500
        })
      }
    })
    console.groupEnd('MP onLanuch')
  },
  created () {
    // 调用API从本地缓存中获取数据
    /*
     * 平台 api 差异的处理方式:  api 方法统一挂载到 mpvue 名称空间, 平台判断通过 mpvuePlatform 特征字符串
     * 微信：mpvue === wx, mpvuePlatform === 'wx'
     * 头条：mpvue === tt, mpvuePlatform === 'tt'
     * 百度：mpvue === swan, mpvuePlatform === 'swan'
     * 支付宝(蚂蚁)：mpvue === my, mpvuePlatform === 'my'
     */
    // const that = this
    // 获取用户当前的授权状态。本项目里判断用户是否已授权登录
    wx.getSetting({
      success (res) {
        console.log('用户信息内容：', res)
        let authSetting = res.authSetting
        if (authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) => {
              console.log('获取用户信息', res)
              mpvue.setStorageSync('userInfo', res.userInfo)
            }
          })
        } else {
          console.log('用户没有授权，发起授权')
          wx.authorize({
            scope: 'scope.userInfo',
            success (res) {
              console.log('用户已经同意授权', res)
            }
          })
        }
      }
    })
  },
  onUnload () {
    console.group('AppUnload')

    console.groupEnd('AppUnload')
  },
  onLoad (option) {
    console.group('ApponLoad')

    console.groupEnd('ApponLoad')
  }
}
</script>
